<template>
    <el-form ref="unitRef" :model="form" :rules="rules" label-width="96px" :disabled="opType==2||opType==3">
        <el-card class="w-full mt-[10px]">
            <CardHead> 基本信息</CardHead>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="机构名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入机构名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                    <el-form-item label="机构编号" prop="code">
                        <el-input v-model="form.code" placeholder="请输入机构编号" />
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="负责人" prop="chargerId">
                        <!-- <el-input v-model="form.chargerId" placeholder="请输入负责人" /> -->
                        <el-select id="formChargerId"
                            v-model="form.chargerId"
                            placeholder="请输入负责人"
                            filterable
                            remote
                            reserve-keyword
                            :remote-method="remoteMethod"
                            :loading="loading"
                            @change="handleChangeCharger"
                        >
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                                <template #default>  
                                    {{ item.label }}（{{item.account}}，{{ item.unitName}}）
                                </template>  
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                    <el-form-item label="联系人" prop="contactsId">
                        <!-- <el-input v-model="form.contactsId" placeholder="请输入联系人" /> -->
                        <el-select id="formContactsId"
                            v-model="form.contactsId"
                            placeholder="请输入联系人"
                            filterable
                            remote
                            reserve-keyword
                            :remote-method="remoteMethod"
                            :loading="loading"
                            @change="handleChangeContacts"
                        >
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                                <template #default>  
                                    {{ item.label }}（{{item.account}}，{{ item.unitName}}）
                                </template>  
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="机构级别" prop="levelId">
                        <el-radio-group v-model="form.levelId">
                        <el-radio
                            v-for="dict in cfg_category_jgjb"
                            :key="dict.value"
                            :value="dict.value"
                        >{{dict.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                    <el-form-item label="成立时间" prop="unitCreateDate">
                        <el-date-picker clearable
                        v-model="form.unitCreateDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择成立时间"
                        style="width: 100%;">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="6">
                    <el-form-item label="挂靠单位" prop="upUnitId">
                        <el-select v-model="form.upUnitId" placeholder="请选择挂靠单位">
                        <el-option
                            v-for="dict in cfg_category_gkdw"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6"></el-col>
                <el-col :span="6">
                    <el-form-item label="对应人事单位" prop="hrUnitId">
                        <el-select v-model="form.hrUnitId" placeholder="请选择对应人事单位">
                        <el-option
                            v-for="dict in cfg_category_ssrsdw"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="6">
                    <el-form-item label="电话" prop="tel">
                        <el-input v-model="form.tel" placeholder="请输入电话" />
                    </el-form-item>
                </el-col>
                <el-col :span="6"></el-col>
                <el-col :span="6">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="form.email" placeholder="请输入邮箱" />
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="地址" prop="address">
                        <el-input v-model="form.address" placeholder="请输入地址" />
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                    <el-form-item label="邮编" prop="postalCode">
                        <el-input v-model="form.postalCode" placeholder="请输入邮编" />
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="网址" prop="website">
                        <el-input v-model="form.website" placeholder="请输入网址" />
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                    <el-form-item label="传真" prop="fax">
                        <el-input v-model="form.fax" placeholder="请输入传真" />
                    </el-form-item> 
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="附件" prop="fileIds" :class="{ delDisabled: opType==2||opType==3 }"> 
                        <file-upload v-model="form.fileIds" :limit=10 :fileSize=20 :fileType="['doc','docx','xls','xlsx','ppt','pptx','txt','pdf']" :isShowTip="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="6">
                    <el-form-item label="上轮评估时间" prop="prevEvaluateTime">
                        <el-date-picker clearable
                        v-model="form.prevEvaluateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择上轮评估时间">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6"></el-col>
                <el-col :span="10">
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="22">
                    <el-form-item label="上轮评估结果" prop="prevEvaluateResult">
                        <el-input v-model="form.prevEvaluateResult" type="textarea" placeholder="请输入内容" />
                    </el-form-item>
                </el-col>
                <el-col :span="1"></el-col>
            </el-row>
        </el-card>

        <el-card class="w-full mt-[10px]">
            <CardHead> 科技部统计信息</CardHead>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="批准建设部门" prop="approveDept">
                        <el-input v-model="form.approveDept" placeholder="请输入批准建设部门" />
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                    <el-form-item label="机构类别" prop="researchTypeId">
                        <el-select v-model="form.researchTypeId" placeholder="请选择机构类别">
                        <el-option
                            v-for="dict in cfg_category_jglb"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="6">
                    <el-form-item label="批复筹建时间" prop="approveDate">
                        <el-date-picker clearable
                        v-model="form.approveDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择批复筹建时间">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6"></el-col>
                <el-col :span="6">
                    <el-form-item label="验收通过时间" prop="unitCheckDate">
                        <el-date-picker clearable
                        v-model="form.unitCheckDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择验收通过时间">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="10">
                    <el-form-item label="是否对外开放" prop="isOpen">
                        <el-radio-group v-model="form.isOpen">
                        <el-radio
                            v-for="dict in yes_no"
                            :key="dict.value"
                            :value="dict.value"
                        >{{dict.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="2"></el-col>
                <el-col :span="6">
                    <el-form-item label="是否属于合建" prop="isCombined">
                        <el-radio-group v-model="form.isCombined">
                        <el-radio
                            v-for="dict in yes_no"
                            :key="dict.value"
                            :value="dict.value"
                        >{{dict.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="5"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="22">
                    <el-form-item label="主要技术领域" prop="techField">
                        <el-input v-model="form.techField" type="textarea" placeholder="请输入内容" />
                    </el-form-item>
                </el-col>
                <el-col :span="1"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="22">
                    <el-form-item label="主要学科领域" prop="subjectField">
                        <el-input v-model="form.subjectField" type="textarea" placeholder="请输入内容" />
                    </el-form-item>
                </el-col>
                <el-col :span="1"></el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="1"></el-col>
                <el-col :span="22">
                    <el-form-item label="备注" prop="intro">
                        <el-input v-model="form.intro" type="textarea" placeholder="请输入内容" />
                    </el-form-item>
                </el-col>
                <el-col :span="1"></el-col>
            </el-row>
        </el-card>

<!--
    <el-form-item label="审核状态" prop="checkStatus">
        <el-input v-model="form.checkStatus" placeholder="请输入审核状态" />
    </el-form-item>
    <el-form-item label="审核时间" prop="checkDate">
        <el-input v-model="form.checkDate" placeholder="请输入审核时间" />
    </el-form-item>
    <el-form-item label="审核人" prop="checker">
        <el-input v-model="form.checker" placeholder="请输入审核人" />
    </el-form-item>

    <el-form-item label="联系人ID" prop="contactsId">
        <el-input v-model="form.contactsId" placeholder="请输入联系人ID" />
    </el-form-item>
    <el-form-item label="负责人ID" prop="chargerId">
        <el-input v-model="form.chargerId" placeholder="请输入负责人ID" />
    </el-form-item>

    <el-form-item label="平台简介">
        <editor v-model="form.platformSummary" :min-height="192"/>
    </el-form-item>

    <el-form-item label="unitId" prop="unitId">
        <el-input v-model="form.unitId" placeholder="请输入unitId" />
    </el-form-item>

    <el-form-item label="导入数据待完善状态" prop="completeDataStatus">
        <el-radio-group v-model="form.completeDataStatus">
        <el-radio
            v-for="dict in sys_job_status"
            :key="dict.value"
            :value="dict.value"
        >{{dict.label}}</el-radio>
        </el-radio-group>
    </el-form-item>
-->
    </el-form>
</template>

<script setup>
//import { defineProps } from 'vue'
import cloneDeep from 'lodash/cloneDeep';  
import useUserStore from '@/store/modules/user';
import CardHead from "./CardHead.vue";
import { listUnit, getUnit, delUnit, addUnit, updateUnit, getCategoryData, getKyryByName, addStartWorkflow, addAndPass, editStartWorkflow, editAndPass, getCurRole } from "@/api/research/unit";

const { proxy } = getCurrentInstance();
const { yes_no } = proxy.useDict('yes_no');
const userStore = useUserStore();
const unitAdminScopeRealArr = userStore.unitAdminScopeReal?userStore.unitAdminScopeReal.split(","):[];

const cfg_category_jgjb = ref([]);
const cfg_category_jglb = ref([]);
const cfg_category_gkdw = ref([]);
const cfg_category_ssrsdw = ref([]);

const emit = defineEmits(['refreshUnitList']);  

const props = defineProps({
  opType: {  
    type: Number,
    required: true,
    default: 0      // 默认值  0:add 1:edit 2:check 3:view
  },
  opUnitInfo: {  
    type: Object,
    required: false,
  }
}) 

const data = reactive({
  form: {},
  rules: {
    name: [
      { required: true, message: "机构名称不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "机构编号不能为空", trigger: "blur" }
    ],
    charger: [
      { required: true, message: "负责人不能为空", trigger: "blur" }
    ],
    contacts: [
      { required: true, message: "联系人不能为空", trigger: "blur" }
    ],
    chargerId: [
      { required: true, message: "负责人不能为空", trigger: "blur" }
    ],
    contactsId: [
      { required: true, message: "联系人不能为空", trigger: "blur" }
    ],
    upUnitId: [
      { required: true, message: "挂靠单位不能为空", trigger: "change" }
    ],
    levelId: [
      { required: true, message: "机构级别不能为空", trigger: "change" }
    ],
    email: [
      { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
    ],
    tel: [
      { pattern: /^(1[3-9]\d{9}|0?\d{2,3}-\d{7,8}|\d{7,8})$/, message: "请输入正确的电话", trigger: "blur" }
    ],
  }
});

const { form, rules } = toRefs(data);

const options = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    getKyryByName(query).then(res => {
        res.data.map(item => {item.value = item.id; item.label = item.name;});
        if (getCurRole() === "biz_kyms") {
            //科研秘书在创建科研平台时，负责人只能选择在他管理范围部门内的       //机构人员并未作此限制
            options.value = res.data.filter(item=>(unitAdminScopeRealArr).includes(item.unitId)||item.id===form.chargerId||item.id===form.value.contactsId);
        } else {
            options.value = res.data;
        }
        loading.value = false
    })
  } else {
    options.value = []
  }
}

onMounted(() => {
    getCategoryData(cfg_category_jgjb, {bizName:"机构级别"});
    getCategoryData(cfg_category_jglb, {bizName:"机构类别"}, true);
    getCategoryData(cfg_category_gkdw, {bizName:"挂靠单位"}, true, /*()=>{if (getCurRole() === "biz_kyms") {cfg_category_gkdw.value = cfg_category_gkdw.value.filter(item=>(unitAdminScopeRealArr).includes(item.value))}}*/);
    getCategoryData(cfg_category_ssrsdw, {bizName:"所属人事单位"}, true);

    //reset();
    switch (props.opType) {
        case 0:
            break;
        case 1:
        case 2:
        case 3:
            form.value = cloneDeep(props.opUnitInfo);
            remoteMethod(form.value.charger);
            if(form.value.charger !== form.value.contacts) {
                remoteMethod(form.value.contacts);
            }
            break;
        default:
            proxy.$modal.msgError("未知操作");
            return;
    }
})

function handleChangeCharger(params) {
    const selectedOption = options.value.find(option => option.id === params);  
    form.value.charger = selectedOption ? selectedOption.name : '';
    form.value.upUnitId = selectedOption ? selectedOption.unitId : '';
    if(form.value.chargerId){
        proxy.$refs["unitRef"].clearValidate('chargerId');
    }
}

function handleChangeContacts(params) {
    const selectedOption = options.value.find(option => option.id === params);  
    form.value.contacts = selectedOption ? selectedOption.name : '';
    if(form.value.contactsId){
        proxy.$refs["unitRef"].clearValidate('contactsId');
    }
}

//保存
function save() {
    proxy.$refs["unitRef"].validate(valid => {
        if (valid) {
            if (props.opType == 1 && form.value.id != null) {
                updateUnit(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    emit('refreshUnitList', true);
                });
            } else if (props.opType == 0 && !form.value.id) {
                addUnit(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    emit('refreshUnitList');
                });
            }
        }
    });
}

//保存并提交
function saveAndSubmit() {
    proxy.$refs["unitRef"].validate(valid => {
        if (valid) {
            if (props.opType == 1 && form.value.id != null) {
                editStartWorkflow(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    emit('refreshUnitList');
                });
            } else if (props.opType == 0 && !form.value.id) {
                addStartWorkflow(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    emit('refreshUnitList');
                });
            }
        }
    });
}

//保存并通过
function saveAndPass() {
    proxy.$refs["unitRef"].validate(valid => {
        if (valid) {
            if (props.opType == 1 && form.value.id != null) {
                editAndPass(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    emit('refreshUnitList');
                });
            } else if (props.opType == 0 && !form.value.id) {
                addAndPass(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    emit('refreshUnitList');
                });
            }
        }
    });
}

//关闭
function cancel() {
    //reset();
    proxy.resetForm("unitRef");
}

defineExpose({save,saveAndSubmit,saveAndPass,cancel});
</script>

<style scoped lang="scss">
@import url("../index.scss");
</style>